package com.yt.bigdata;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.sql.*;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class PreparedStmtExample {

    public static void main(String args[]) throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://10.192.147.1:9030/tpcds?useSSL=false";
        System.out.println(url.hashCode());
        String username = "root";
        String password = "root";
        Connection connection = DriverManager.getConnection(url, username, password);
        String sql = "select * from data_load.ods_bsn_track_detail_dup where sk = ? limit 10";
        PreparedStatement preStatement = connection.prepareStatement(sql);
        preStatement.setString(1, "f1c7");
        preStatement.close();
        preStatement = connection.prepareStatement(sql);
        preStatement.setString(1, "c25d");
        ResultSet resultSet = preStatement.executeQuery();

        List<Map<String, Object>> list = getList(resultSet);
        System.out.println(JSON.toJSONString(list, SerializerFeature.PrettyFormat));

    }

    public static List<Map<String, Object>> getList(ResultSet rs) {
        List<Map<String, Object>> targets = new ArrayList<>();
        try {
            ResultSetMetaData rsmd = rs.getMetaData();
            int colCnt = rsmd.getColumnCount();
            String[] columnNames = new String[colCnt];
            Object[] columnValues = new Object[colCnt];
            Class<?>[] columnTypes = new Class<?>[colCnt];
            for (int i = 0; i < colCnt; i++) {
                columnNames[i] = rsmd.getColumnLabel(i + 1);
            }
            while (rs.next()) {
                for (int i = 0; i < colCnt; i++) {
                    String columnName = columnNames[i];
                    Object columnValue = rs.getObject(columnName);
                    Class<?> columnType = null;
                    if (columnValue != null) {
                        columnType = columnValue.getClass();
                    }
                    columnValues[i] = columnValue;
                    columnTypes[i] = columnType;
                }
                Map<String, Object> target = new LinkedHashMap<>();
                for (int i = 0; i < colCnt; i++) {
                    String columnName = columnNames[i];
                    Object columnValue = columnValues[i];
                    target.put(columnName, columnValue);
                }
                targets.add(target);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return targets;
    }


}
